package com.fingard.dsp.interact.oss.aliyun;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import com.fingard.FGBiz;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.interact.DownloadFileReq;
import com.fingard.dsp.interact.DownloadFileResp;
import com.fingard.dsp.interact.FileServerInvokerBase;
import com.fingard.dsp.interact.GenerateUrlReq;
import com.fingard.dsp.interact.GenerateUrlResp;
import com.fingard.dsp.interact.IFileServerInvoker;
import com.fingard.dsp.interact.UploadFileReq;
import com.fingard.dsp.interact.UploadFileResp;
import com.fingard.generalobj.ExecResponse;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;

public class FileServerInvoker extends FileServerInvokerBase implements IFileServerInvoker{
	
	private String logCode = "oss.aliyun"+File.separator+"FileServerInvoker";

	public void setLogCode(String pLogCode) {
		logCode = pLogCode;
	}
	public UploadFileResp uploadFile(UploadFileReq req) {
		UploadFileResp resp = new UploadFileResp();
		resp.isCompleted = false;
		OSSClient ossClient = null;
		try{
			ossClient = new OSSClient(fsSet.ossSet.endpoint, fsSet.ossSet.accessKeyId, fsSet.ossSet.accessKeySecret);
			String upfilename = "ats." + StringHelper.getFileName(req.upFileLocalPath);
			PutObjectResult putResult = ossClient.putObject(fsSet.ossSet.bucket, upfilename, new File(req.upFileLocalPath));
			resp.sbMsg.append("getETag:" + putResult.getETag()+"\r\n");
			resp.sbMsg.append("getResponse:" + putResult.getResponse()+"\r\n");
			resp.sbMsg.append("getRequestId:" + putResult.getRequestId()+"\r\n");
			
	        ossClient.setObjectAcl(fsSet.ossSet.bucket, upfilename, CannedAccessControlList.PublicRead);
	        resp.isCompleted = true;
	        resp.rtnFileId = upfilename;
	        
	        FGBiz.logTrace.debug("aliyunOss", resp.sbMsg.toString());
			
		}catch (OSSException oe) {
			resp.sbMsg.append("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
			resp.sbMsg.append("Error Message: " + oe.getErrorCode());
			resp.sbMsg.append("Error Code:       " + oe.getErrorCode());
			resp.sbMsg.append("Request ID:      " + oe.getRequestId());
			resp.sbMsg.append("Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
        	resp.sbMsg.append("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
        	resp.sbMsg.append("Error Message: " + ce.getMessage());
        }catch(Throwable e){
			resp.sbMsg.append(LogHelper.getStackTrace(e)+"\r\n");
			FGBiz.limitMsg.exception("oss.aliyun.uploadFile", e);
		}finally{
			if(ossClient != null){
				try{
					ossClient.shutdown();
				}catch(Throwable ex){
					FGBiz.limitMsg.exception("oss.aliyun.uploadFile", ex);
				}
			}
		}
		
		return resp;
	}

	public DownloadFileResp downloadFile(DownloadFileReq req) {
		DownloadFileResp resp = new DownloadFileResp();
		resp.isCompleted = false;
		OSSClient ossClient = null;
		InputStream inStream = null;
		try{
			ossClient = new OSSClient(fsSet.ossSet.endpoint, fsSet.ossSet.accessKeyId, fsSet.ossSet.accessKeySecret);
			OSSObject ossObj = ossClient.getObject(new GetObjectRequest(fsSet.ossSet.bucket, req.fileId));
			inStream = ossObj.getObjectContent();
			ByteArrayOutputStream outArrStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[20480];// 20k
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
            	outArrStream.write(buffer, 0, len);
            }
            resp.fileBytes = outArrStream.toByteArray();
            resp.isCompleted = true;
            outArrStream.close();
		}catch(Throwable e){
			resp.sbMsg.append(LogHelper.getStackTrace(e)+"\r\n");
			FGBiz.limitMsg.exception("oss.aliyun.downloadFile", e);
		}finally{
			if(inStream!=null){
				try{
					inStream.close();
				}catch(Throwable ex){
					FGBiz.limitMsg.exception("oss.aliyun.downloadFile", ex);
				}
			}
			if(ossClient != null){
				try{
					ossClient.shutdown();
				}catch(Throwable ex){
					FGBiz.limitMsg.exception("oss.aliyun.downloadFile", ex);
				}
			}
		}
		
		return resp;
	}

	public GenerateUrlResp generateUrl(GenerateUrlReq req) {
		GenerateUrlResp resp = new GenerateUrlResp();
		resp.isCompleted = false;
		OSSClient ossClient = null;
		try{
			ossClient = new OSSClient(fsSet.ossSet.endpoint, fsSet.ossSet.accessKeyId, fsSet.ossSet.accessKeySecret);
			Date expireDate = DateHelper.addDays(new Date(), fsSet.ossSet.urlLimitDays);
			URL url = ossClient.generatePresignedUrl(fsSet.ossSet.bucket, req.fileId, expireDate);
			resp.resultUrl = url.toString();
			resp.isCompleted = true;
		}catch(Throwable e){
			resp.sbMsg.append(LogHelper.getStackTrace(e)+"\r\n");
			FGBiz.limitMsg.exception("oss.aliyun.generateUrl", e);
		}finally{
			
			if(ossClient != null){
				try{
					ossClient.shutdown();
				}catch(Throwable ex){
					FGBiz.limitMsg.exception("oss.aliyun.generateUrl", ex);
				}
			}
		}
		return resp;
	}
	
	public ExecResponse pushData(ArrayList<ReceiptData> pDataList) {
		ExecResponse resp = new ExecResponse();
		resp.logMsg = "未实现该接口";
		return resp;
	}
}
